package com.pointstar.dp.tree;

/**
 * 南软2004T1
 * 交换二叉树中每个节点左右子女
 *
 * @author 朱科睿
 */
public class ExchangeSubTree {

    public static void main(String[] args) {
        BinarySearch third1 = new BinarySearch(2);
        BinarySearch third3 = new BinarySearch(5);
        BinarySearch second2 = new BinarySearch(6);
        second2.setLeft(third3);
        BinarySearch second1 = new BinarySearch(3);
        second1.setLeft(third1);
        BinarySearch root = new BinarySearch(4);
        root.setLeft(second1);
        root.setRight(second2);
        System.out.println("交换前：");
        print(root);
        exchangeSubTree(root);
        System.out.println("\n交换后：");
        print(root);
    }

    /**
     * 交换二叉树中每个节点左右子女
     *
     * @param root 根节点
     */
    private static void exchangeSubTree(BinarySearch root) {
        BinarySearch temp = new BinarySearch();
        if (root != null) {
            temp.setLeft(root.getLeft());
            root.setLeft(root.getRight());
            root.setRight(temp.getLeft());
            exchangeSubTree(root.getLeft());
            exchangeSubTree(root.getRight());
        }
    }

    private static void print(BinarySearch root) {

        if (root != null) {
            System.out.print(root.getData() + "->");
            print(root.getLeft());
            print(root.getRight());
        }
    }
}
